import type { Menu, Role } from '@/composables/types/userInfo'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const usePermissionStore = defineStore('permission', () => {
  const menuList = ref<Menu[]>([])
  const roleList = ref<Role[]>([])

  function setMenuList(menus: Menu[]) {
    menuList.value = menus || []
  }

  function setRoleList(roles: Role[]) {
    roleList.value = roles || []
  }

  /**
   * 检查用户是否有指定权限
   * @param permission 权限名称或权限数组 permission 字段
   * @returns 如果用户有指定权限则返回true，否则返回false
   */
  function hasPermission(permission: string[] | string): boolean {
    if (Array.isArray(permission)) {
      return permission.some(item => menuList.value.some(menu => menu.permission === item))
    }
    return menuList.value.some(item => item.permission === permission)
  }

  /**
   * 检查用户是否有指定角色
   * @param role 角色名称或角色数组 role_key 字段
   * @returns 如果用户有指定角色则返回true，否则返回false
   */
  function hasRole(role: string[] | string): boolean {
    if (Array.isArray(role)) {
      return role.some(item => roleList.value.some(role => role.role_key === item))
    }
    return roleList.value.some(item => item.role_key === role)
  }

  return {
    menuList,
    roleList,
    setMenuList,
    setRoleList,
    hasPermission,
    hasRole,
  }
})
